const query = require('../../dbConfig/index')

const get = async (ctx,next)=>{
	const body = ctx.request.body
	const offset = (body.pageNumber - 1) * Number(body.pageSize);  
	let sql = 'SELECT * FROM attendance';  
	let params = [];  
	if (body.student_id) {  
		sql += sql.includes('WHERE')? ' and student_id=?': ' WHERE student_id=?';  
		params.push(body.student_id);  
	}
	if (body.classes_id) {  
		sql += sql.includes('WHERE')?  'and classes_id=?':' WHERE classes_id=?';  
		params.push(body.classes_id);  
	}
	if (body.rewardsType) {  
		sql +=sql.includes('WHERE')? ' and rewards_type=?': ' WHERE rewards_type=?';  
		params.push(body.rewardsType);  
	}
	if (body.createtime) {  
		sql +=sql.includes('WHERE')? ' and createtime=?': ' WHERE createtime=?';  
		params.push(body.createtime);
	}
	  sql += ' LIMIT ? OFFSET ?';  
	  params.push(Number(body.pageSize));  
	  params.push(offset);
	const res = await query(sql,params)
	const total = await query(`SELECT COUNT(*) as total FROM attendance`)
	if(res.length>0){
		ctx.body={code:200,data:{records:res,total:total[0].total},msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'失败'}
	}
}

const updata = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`UPDATE attendance SET student_id=?,student_name=?,classes_id=?,createtime=?,rewards_type=?,rewards_description=? WHERE rewards_id='${body.rewards_id}'`,[body.student_id,body.student_name,body.classes_id,body.createtime,body.rewards_type,body.rewards_description])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
	
}
const add = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`INSERT INTO attendance (student_id,student_name,classes_id,createtime,rewards_type,rewards_description) VALUES (?,?,?,?,?,?)`,[body.student_id,body.student_name,body.classes_id,body.createtime,body.rewards_type,body.rewards_description])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const remove = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`DELETE FROM attendance WHERE rewards_id=${body.id}`)
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
module.exports = {
	get,getItem,
	add,updata,remove
}